package com.ruoyi.mixuebingcheng.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.mixuebingcheng.domain.ShoppingCart;
import com.ruoyi.mixuebingcheng.domain.User;
import com.ruoyi.mixuebingcheng.domain.bo.ShoppingCartBo;
import com.ruoyi.mixuebingcheng.mapper.ShoppingCartMapper;
import com.ruoyi.mixuebingcheng.mapper.WxUserMapper;
import com.ruoyi.mixuebingcheng.service.IShoppingCartService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.mixuebingcheng.domain.bo.OrderTestBo;
import com.ruoyi.mixuebingcheng.domain.vo.OrderTestVo;
import com.ruoyi.mixuebingcheng.domain.OrderTest;
import com.ruoyi.mixuebingcheng.mapper.OrderTestMapper;
import com.ruoyi.mixuebingcheng.service.IOrderTestService;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2023-10-27
 */
@RequiredArgsConstructor
@Service
public class OrderTestServiceImpl implements IOrderTestService {

    private final OrderTestMapper baseMapper;
    private final ShoppingCartMapper shoppingCartMapperMapper;
    private final IShoppingCartService iShoppingCartService;
    private final WxUserMapper wxUserMapper;
    /**
     * 查询【请填写功能名称】
     */
    @Override
    public OrderTestVo queryById(Long id){
        return baseMapper.selectOrderDetailVoById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @Override
    public TableDataInfo<OrderTestVo> queryPageList(OrderTestBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<OrderTest> lqw = buildQueryWrapper(bo);
        Page<OrderTestVo> result = baseMapper.selectOrderDetail(pageQuery.build(),  lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 根据订单 status 查询订单列表
     * @return
     */
    @Override
    public List<OrderTestVo> queryByStatus(Integer status) {
        LambdaQueryWrapper<OrderTest> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OrderTest::getStatus, status);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @Override
    public List<OrderTestVo> queryList(OrderTestBo bo) {
        LambdaQueryWrapper<OrderTest> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }


    private LambdaQueryWrapper<OrderTest> buildQueryWrapper(OrderTestBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<OrderTest> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, OrderTest::getUserId, bo.getUserId());
        lqw.eq(bo.getMethod() != null, OrderTest::getMethod, bo.getMethod());
        lqw.eq(StringUtils.isNotBlank(bo.getShop()), OrderTest::getShop, bo.getShop());
        lqw.eq(bo.getStatus() != null, OrderTest::getStatus, bo.getStatus());
        lqw.eq(bo.getTime() != null, OrderTest::getTime, bo.getTime());
        lqw.eq(bo.getGoodNum() != null, OrderTest::getGoodNum, bo.getGoodNum());
        lqw.eq(bo.getAmount() != null, OrderTest::getAmount, bo.getAmount());
        lqw.eq(bo.getPickupCode() != null, OrderTest::getPickupCode, bo.getPickupCode());
        lqw.eq(StringUtils.isNotBlank(bo.getOrderNumber()), OrderTest::getOrderNumber, bo.getOrderNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getNotes()), OrderTest::getNotes, bo.getNotes());
        lqw.orderByDesc(true,  OrderTest::getTime);
        return lqw;
    }

    /**
     * 新增【请填写功能名称】
     */
    @Override
    @Transactional
    public Boolean insertByBo(OrderTestBo bo) {
        Date d = new Date();
        bo.setTime(d);

//        金额 总数量
        LambdaQueryWrapper<ShoppingCart> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getStatus() != null, ShoppingCart::getStatus, 1);
        lqw.eq(bo.getUserId() != null, ShoppingCart::getUserId, bo.getUserId());
        List<ShoppingCart> shoppingCartList = shoppingCartMapperMapper.selectList(lqw);
        BigDecimal account = new BigDecimal(0);
        Long totalNum = 0L;
        for(ShoppingCart shoppingCart: shoppingCartList) {
            if(shoppingCart.getPrice()==null)shoppingCart.setPrice(new BigDecimal(0));
            account = account.add(BigDecimal.valueOf(shoppingCart.getNum()).multiply(shoppingCart.getPrice()));
            totalNum += shoppingCart.getNum();
        }
        bo.setGoodNum(totalNum);
        bo.setAmount(account);
//        根据金额，增加用户雪王币
//        User user = wxUserMapper.selectById(bo.getUserId());
//        Long result = account.longValue();
//        user.setXuewang(user.getXuewang()+result*10);
//        wxUserMapper.updateById(user);

//        订单号 当前时间
        SimpleDateFormat sbf = new SimpleDateFormat("yyyyMMddHHmmss");
        bo.setOrderNumber(sbf.format(d));
//      取餐号码 当天第一个为1 之后取当天第一个最大+1
        bo.setPickupCode(baseMapper.maxPickupCode());

        OrderTest add = BeanUtil.toBean(bo, OrderTest.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            baseMapper.settleAccount(bo.getId(),bo.getUserId());
        }
        return flag;
    }

    /**
     * 修改【请填写功能名称】
     */
    @Override
    @Transactional
    public Boolean updateByBo(OrderTestBo bo) {
        OrderTest update = BeanUtil.toBean(bo, OrderTest.class);
        validEntityBeforeSave(update);
        if(bo.getStatus()==1) {
//        取餐后,根据金额，增加用户雪王币，每1元加10币
            User user = wxUserMapper.selectById(bo.getUserId());
            Long result = update.getAmount().longValue();
            user.setXuewang(user.getXuewang() + result * 10);
//            判断是否是新用户，每1元加20币
            OrderTestBo query = new OrderTestBo();
            query.setUserId(bo.getUserId());
            query.setStatus(1L);
            List<OrderTest> orderTestList  = baseMapper.selectList(buildQueryWrapper(query));
            if(orderTestList.size()==0){
                user.setXuewang(user.getXuewang() + result * 10);

            }
            wxUserMapper.updateById(user);
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OrderTest entity){

    }

    /**
     * 批量删除【请填写功能名称】
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional
    public Boolean buyNow(ShoppingCartBo bo) {
        bo.setStatus(0L);
        OrderTestBo orderTestBo = new OrderTestBo();
        orderTestBo.setMethod(0L);
        orderTestBo.setShop("蜜雪冰城(浙江农林C6店)");
        orderTestBo.setGoodNum(bo.getNum());
        orderTestBo.setAmount(bo.getAmount());
        orderTestBo.setUserId(bo.getUserId());
        orderTestBo.setStatus(0L);
        Date d = new Date();
        orderTestBo.setTime(d);

//        根据金额，增加用户雪王币
//        User user = wxUserMapper.selectById(bo.getUserId());
//        Long result = orderTestBo.getAmount().longValue();
//        user.setXuewang(user.getXuewang()+result*10);
//        wxUserMapper.updateById(user);


        //        订单号 当前时间
        SimpleDateFormat sbf = new SimpleDateFormat("yyyyMMddHHmmss");
        orderTestBo.setOrderNumber(sbf.format(d));
//      取餐号码 当天第一个为1 之后取当天第一个最大+1
        orderTestBo.setPickupCode(baseMapper.maxPickupCode());
        OrderTest add = BeanUtil.toBean(orderTestBo, OrderTest.class);

        baseMapper.insert(add);
        bo.setOrderId(add.getId());
        iShoppingCartService.insertByBo(bo);

        return true;
    }
}
